package com.mysoft.main.main.controller;

import com.mysoft.common.entity.User;
import com.mysoft.common.utils.JWTUtil;
import com.mysoft.common.vo.LoginUser;
import com.mysoft.main.main.web.Result;
import com.mysoft.service.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: JohnCoding
 * @Description:
 * @date: 2019/12/23 16:47
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user) throws UnsupportedEncodingException {
        log.warn("执行登录操作!");
        Subject subject = SecurityUtils.getSubject();
        //先执行登录验证的过滤操作,才会执行后面这些乱七八糟的异常
        //throw new MyException("测试自定义异常!");
        //throw  new MyException("我的模拟业务代码的异常!");
        User user1 = null;
        try {
            user1 = userService.getByUserName(user.getUsername());
        } catch (Exception e) {
            System.out.println("该用户名或者密码错误,请检查后再登录!");
        }
        if(null == user1){
            return new Result("没有该用户，请检查！");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user1);
        //根据电话号码和密码加密生成token
        String token = JWTUtil.sign(user1.getUsername(), user1.getPassword());
        loginUser.setToken(token);
        if (loginUser != null) {
            return new Result().ok(loginUser);
        }
        return new Result().error("登录失败!");
    }

}
